package com.nekonomics
package utils

import com.nekonomics.utils.magic.{SqlMagic, TypeMagic}

import scala.quoted.*
import doobie.*
import doobie.implicits.*
import doobie.util.Write
import zio.ZIO

object SqlUtil {
  
  
  def fieldsWithAlias(fields: List[String], tableAlias: Option[String]): String =
    fields.map(field => tableAlias.fold(field)(alias => s"$alias.$field"))
      .mkString(",")


  inline def selectFromWhereOpt[T](cond: Option[Fragment] = None): Fragment = {
    val fields = SqlMagic.fieldSnakeNames4Select[T]
    val tableName = SqlMagic.tableName4Sql[T]
    val baseFr = fr"SELECT " ++ Fragment.const(fields) ++ fr" FROM " ++ Fragment.const(tableName)
    cond.fold(baseFr)(cond => baseFr ++ fr" where " ++ cond)
  }

//  inline def insertWithUpd0[T: Write](obj: T): Update0 = {
//    val sql = SqlMagic.insertSql[T]
//    Update[T](sql).toUpdate0(obj)
//  }


//  inline def insertReturnOpt[T](obj: T, excludeFields: List[String]=Nil, retnField: Option[String] = None): Fragment = {
//    val baseSql = SqlMagic.insertSqlNoHolder[T]
//    val dynamicValues = s"(${obj.asInstanceOf[Product].productIterator.mkString(", ")})"
//    retnField.fold(Fragment.const(baseSql + dynamicValues)) (
//      retn => Fragment.const(baseSql + dynamicValues + " RETURNING " ) ++ fr"${SqlMagic.camelToSnake(retn)}"
//    )
//  }





  //  private def insertWithParamsImpl[T: {Type, Write}](obj: T)(using q: Quotes, u: ToExpr[Update0]): Expr[Update0] = {
  //    Expr(Update[T](insertWithTemplate[T]).toUpdate0(obj))
  //  }


}
